package com.magiccompass.alipay.barcode.schedule;

import java.util.ArrayList;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.magiccompass.alipay.barcode.model.DailySettlementEmailModel;
import com.magiccompass.alipay.barcode.service.MerchantBusinessService;
import com.magiccompass.alipay.barcode.util.DailySettlementDemosticBatchFileHandler;
import com.magiccompass.alipay.barcode.util.DailySettlementFileEmailHandler;
import com.magiccompass.alipay.barcode.util.DailySettlementFileHandler;
import com.magiccompass.alipay.barcode.util.EmailUtil;

@Component
public class DailySettlementFileTask {
	@Resource(name="merchantBusinessService")
	private MerchantBusinessService merchantBusinessService;
	/*
	 * cron format: sec min hour day mon week
	 */
	//@Scheduled(cron="0 58 14 * * *")
	@Scheduled(cron="0 20 0 * * *") // product server
	public void makeDailySettlementFile(){
		DailySettlementFileHandler dsfh = DailySettlementFileHandler.getInstance();
		dsfh.setMerchantBusinessService(merchantBusinessService);
		dsfh.startMakeDailySettlementFile();		
	}
	
	//@Scheduled(cron="0 3 17 * * *")
	@Scheduled(cron="0 30 0 * * *")  // product server, must after makeDailySettlementFile(), because it need DailySettlementFileHandler.dailySettlementRecordsAdmin
	public void makeBatchUploadFile(){
		DailySettlementDemosticBatchFileHandler dsdbfh = DailySettlementDemosticBatchFileHandler.getInstance();
		dsdbfh.setMerchantBusinessService(merchantBusinessService);
		dsdbfh.startMakeBatchUploadFile();		
	}
	
	//@Scheduled(cron="30 58 14 * * *") 
	@Scheduled(cron="0 10 1 * * *")  // product server
	public void sendDailySettlementFileByEmail(){
		EmailUtil eu = new EmailUtil();
		for(DailySettlementEmailModel dsem:DailySettlementFileEmailHandler.dailySettlementEmailBatchList){
			if(dsem.getEmailCCList() != null && !dsem.getEmailCCList().isEmpty()){
				eu.sendEmailWithAttachment(dsem.getReceiverEmailAddress(), dsem.getEmailTitle(),
						dsem.getEmailBodyMessage(), dsem.getReportFileAbsolutePath(),dsem.getEmailCCList().toArray(new String[0]));
			}else{
				eu.sendEmailWithAttachment(dsem.getReceiverEmailAddress(), dsem.getEmailTitle(),
						dsem.getEmailBodyMessage(), dsem.getReportFileAbsolutePath());
			}
			
		}
		// reset daily batch list. otherwise, it still contain old already send email
		// 2016-04-21 George found this bug
		DailySettlementFileEmailHandler.dailySettlementEmailBatchList =  new ArrayList<DailySettlementEmailModel>();
	}
}